﻿/****************************** 模块头 ******************************\
* 模块名:  Media.cs
* 项目名:  DingTalkAPIHelp
* 版权(c)  auth markeluo.
* 
*说明： Media 用于管理钉钉媒体文件( 图片、语音等媒体资源文件以及普通文件（如doc、ppt）)
* This source is subject to the markeluo
* All other rights reserved.
\***************************************************************************/

using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using DingTalkAPIHelp.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Top.Api.Util;

namespace DingTalkAPIHelp.File
{
    /// <summary>
    /// 钉钉媒体文件管理
    /// </summary>
    public class Media:SysConfigManager
    {
        /// <summary>
        /// 1.上传
        /// </summary>
        /// <param name="mediaType">类型,大小限制，图片1MB,语音2MB AMR格式,普通文件 10MB</param>
        /// <param name="file">文件</param>
        /// <returns></returns>
        public OapiMediaUploadResponse Upload(MediaType mediaType, FileItem file)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/media/upload");

            OapiMediaUploadRequest request = new OapiMediaUploadRequest();
            request.Type = mediaType.ToString();
            request.Media=file; 
            OapiMediaUploadResponse response = client.Execute(request,accessToken);

            return response;
        }

        /// <summary>
        /// 2.下载媒体文件
        /// </summary>
        /// <param name="media"></param>
        public HttpWebResponse DownLoad(string media)
        {
            string url = "https://oapi.dingtalk.com/media/downloadFile";
            IDictionary<string, string> textParams = new Dictionary<string, string>();
            textParams.Add("access_token", accessToken);
            textParams.Add("media_id", media);
            
            if (textParams != null && textParams.Count > 0)
            {
                url =WebUtils.BuildRequestUrl(url, textParams);
            }
            WebUtils _util = new WebUtils();
            HttpWebRequest req = _util.GetWebRequest(url, "GET", null);
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            return rsp;
            ////设置接收对象的范围为0-10000000字节。

            //hwr.AddRange(0, 10000000);

            ////流对象使用完后自动关闭
            //using (Stream stream = hwr.GetResponse().GetResponseStream())
            //{
            //    //文件流，流信息读到文件流中，读完关闭
            //    using (FileStream fs = File.Create(@"c:\gif.png"))
            //    {
            //        //建立字节组，并设置它的大小是多少字节
            //        byte[] bytes = new byte[102400];
            //        int n = 1;
            //        while (n > 0)
            //        {
            //            //一次从流中读多少字节，并把值赋给Ｎ，当读完后，Ｎ为０,并退出循环
            //            n = stream.Read(bytes, 0, 10240);
            //            fs.Write(bytes, 0, n);　//将指定字节的流信息写入文件流中
            //        }
            //    }
            //}
        }
    }
}
